import json
import traceback
from django.http import JsonResponse
from django.views.generic import View
from unit_management.models import Quantity, Unit
from ..utils.related_util.choice_util import get_valid_show_unit_choices_by_quantity
from utils.responseContentUtil import *


class QuantitySelectView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            quantitys = Quantity.objects.filter(valid_flag=True)
            quantity_select_data = []
            for quantity in quantitys:
                quantity_select_data.append(
                    {"value": quantity.uuid, "label": quantity.show_short_name()})
            return make_get_success_response(data=quantity_select_data)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))


class UnitSymbolSelectView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            quantity_id = request.GET.get("quantity_id")
            quantity = Quantity.objects.filter(
                uuid=quantity_id, valid_flag=True).first()
            if not quantity:
                return make_get_error_response(message="量不存在")
            quantity_unit_list = get_valid_show_unit_choices_by_quantity(
                quantity)
            return make_get_success_response(data=quantity_unit_list)
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))


class UnitConversionView(View):
    def get(self, request):
        res = {"code": 400, "message": "", "data": None}
        try:
            get_params = request.GET
            get_params = json.loads(get_params.get("query"))
            quantity_id = get_params.get("quantity_id")
            unit_symbol_from_id = get_params.get("unit_from_id")
            unit_symbol_to_id = get_params.get("unit_to_id")
            value = get_params.get("value")
            quantity = Quantity.objects.filter(
                uuid=quantity_id, valid_flag=True).first()
            if not quantity:
                return make_custom_error_response(message="该量不存在")
            unit_from_entity = Unit.objects.filter(
                uuid=unit_symbol_from_id, valid_flag=True).first()
            if not unit_from_entity:
                return make_custom_error_response(message="转换前单位不存在")
            unit_to_entity = Unit.objects.filter(
                uuid=unit_symbol_to_id, valid_flag=True).first()
            if not unit_to_entity:
                return make_custom_error_response(message="转换后单位不存在")
            if quantity.dimension != unit_from_entity.dimension or quantity.dimension != unit_to_entity.dimension:
                return make_custom_error_response(message="量的量纲与单位的量纲不匹配")
            if not isinstance(value, (float, int)):
                return make_custom_error_response(message="请正确输入转换值")
            # 获取unit_from的转换系数
            unit_from_conversion_list = []
            from_target_unit = unit_from_entity
            while (from_target_unit.root_unit):
                unit_from_conversion_list.append(
                    {"factor": from_target_unit.conversion_factor, "offset": from_target_unit.conversion_offset})
                from_target_unit = from_target_unit.root_unit
            # 获取unit_to的转换系数
            unit_to_conversion_list = []
            to_target_unit = unit_to_entity
            while (to_target_unit.root_unit):
                unit_to_conversion_list.append(
                    {"factor": to_target_unit.conversion_factor, "offset": to_target_unit.conversion_offset})
                to_target_unit = to_target_unit.root_unit
            # 如果两个底端单位不一致，返回错误
            if from_target_unit != to_target_unit:
                return make_custom_error_response(message="转换前后基准单位不一致，请检查单位部分数据")
            # 计算转换结果
            conversion_result = value
            for conversion in unit_from_conversion_list:
                conversion_result = conversion_result * \
                    conversion["factor"] + conversion["offset"]
            for conversion in unit_to_conversion_list:
                conversion_result = (conversion_result - conversion["offset"]) / \
                    conversion["factor"]
            return make_custom_success_response(data={"status": "success",
                                                      "message": "转换成功", "value": conversion_result})
        except Exception as e:
            traceback.print_exc()
            return make_server_error_response(str(e))
